<template>
  <div class="user_collect">
    <!-- 头部导航结构 -->
    <van-nav-bar
      title="我的收藏"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push({ path: '/' })"
    >
      <template #right>
        <van-icon name="wap-home-o" size="5vw" />
      </template>
    </van-nav-bar>
    <!-- 收藏列表 -->
    <div class="list">
      <van-swipe-cell v-for="(item, index) in starLlist" :key="item.id">
        <MyPost :post="item"> </MyPost>
        <template #right>
          <van-button
            square
            text="取消收藏"
            type="danger"
            class="delete-button"
            @click="delStarFn(item.id, index)"
          />
        </template>
      </van-swipe-cell>
      <!-- 没有数据时显示 -->
      <van-empty v-if="starLlist.length === 0" description="空空如野" />
    </div>
  </div>
</template>

<script>
import { updatePostStarByIdAPI } from "../apis/news";
import { getUserStar } from "../apis/user";
import MyPost from "../components/MyPost.vue";
export default {
  components: {
    MyPost,
  },
  data() {
    return {
      starLlist: [],
    };
  },
  async created() {
    //获取收藏列表
    const res = await getUserStar();
    // console.log(res);
    // 由于我的收藏页和首页评论的字段名不一样，需要我们自己处理 map()
    this.starLlist = res.data.data.map((item) => {
      return {
        ...item,
        comment_length: item.comments.length,
      };
    });
  },
  methods: {
    delStarFn(id, index) {
      this.$dialog
        .confirm({
          title: "温馨提示",
          message: "请问是否真的想取消这篇文章的收藏",
        })
        .then(async () => {
          //确定删除
          const res = await updatePostStarByIdAPI(id);
          //   console.log(res);
          if (res.data.message === "取消成功") {
            this.$toast.success("取消成功");
            //删除对应的文章,更新列表
            this.starLlist.splice(index, 1);
          }
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
.delete-button {
  height: 100%;
}
</style>